package cn.slb.im.modules.sys.biz.impl;

import cn.slb.im.modules.sys.biz.AccessTokenBiz;
import cn.slb.im.modules.sys.config.WorkWxConfig;
import cn.slb.im.modules.sys.constant.WorkWxConstant;
import cn.slb.im.modules.sys.dto.AccessTokenResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: NickLi
 * @Description: AccessToken
 * @Date: 2021/12/2 18:00
 */
@Service
@AllArgsConstructor
public class AccessTokenBizImpl implements AccessTokenBiz {

    private final WorkWxConfig workWxConfig;

    private final RestTemplate restTemplate;

    @Override
    public String getAccessToken() {
        String corpId = workWxConfig.getCorpId();
        String corpSecret = workWxConfig.getCorpSecret();
        String baseUrl = workWxConfig.getBaseUrl();
        // 拼装URL
        String url = baseUrl + String.format(WorkWxConstant.GET_TOKEN, corpId, corpSecret);
        AccessTokenResponse accessTokenResponse = restTemplate.getForObject(url, AccessTokenResponse.class);
        if (ObjectUtils.isEmpty(accessTokenResponse)) {
            throw new RuntimeException("获取企业微信AccessToken失败，失败原因：网络出小差了，请稍后再试");
        }
        if (0 != accessTokenResponse.getErrcode()) {
            throw new RuntimeException("获取企业微信AccessToken失败，失败原因：" + accessTokenResponse.getErrmsg());
        }
        return accessTokenResponse.getAccess_token();
    }
}
